package com.dcrzl.shcz.module.info.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.dcrzl.shcz.common.excel.ReviewOrderExcel;
import com.dcrzl.shcz.common.exception.MyException;
import com.dcrzl.shcz.common.utils.PageInfo;
import com.dcrzl.shcz.common.utils.Result;
import com.dcrzl.shcz.common.utils.SysConstant;
import com.dcrzl.shcz.module.info.service.ReviewOrderService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.dcrzl.shcz.common.entity.info.ReviewOrder;

/**
 * 评审流程单
 *
 * @author dcrzl
 * @email 1728795786@qq.com
 * @date 2025-01-01 22:49:28
 */
@Slf4j
@RestController
@RequestMapping("/review/order")
public class ReviewOrderController {
    @Autowired
    private ReviewOrderService reviewOrderService;

    /**
     * 列表
     */
    @GetMapping("/list")
    public Result<List<ReviewOrder>> list(ReviewOrder reviewOrder){
       return reviewOrderService.selectList(reviewOrder);
    }

    /**
    * 列表分页
    */
    @GetMapping("/page")
    public PageInfo<ReviewOrder> page(ReviewOrder reviewOrder){
        return reviewOrderService.selectUPage(reviewOrder);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public Result<ReviewOrder> info(@PathVariable("id") Long id){
		return reviewOrderService.selectById(id);
    }


    /**
     * 保存
     */
    @PostMapping("/save")
    public Result<Integer> save(@RequestBody ReviewOrder reviewOrder){
		return reviewOrderService.insert(reviewOrder);
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public Result<Integer> update(@RequestBody ReviewOrder reviewOrder){
		return reviewOrderService.updateById(reviewOrder);
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    public Result<Integer> delete(@RequestBody Long[] ids){
        return reviewOrderService.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("/download/excel")
    public void download(HttpServletResponse response,ReviewOrder reviewOrder) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            reviewOrder.setPageNumber(null).setPageSize(null);
            Result<List<ReviewOrderExcel>> result = reviewOrderService.selectListByExcel(reviewOrder);
            List<ReviewOrderExcel> reviewOrderExcelList = null;
            if(!result.isSuccess()){
                throw new MyException(result.getMsg());
            }else{
                reviewOrderExcelList = result.getData();
                log.info(JSON.toJSONString(reviewOrderExcelList));
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(System.currentTimeMillis()+"", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), ReviewOrderExcel.class).autoCloseStream(Boolean.FALSE).sheet("")
                    .doWrite(reviewOrderExcelList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Result<String> result = new Result<>();
            result.setMsg(e.getMessage());
            result.setSuccess(false).setCode(SysConstant.SELECT_FAIL_CODE_RES);
            response.getWriter().println(JSON.toJSONString(result));
        }
    }

}
